<!--
 * @Author: Liz.Zheng
 * @Date: 2021-12-27 11:03:25
 * @LastEditTime: 2022-11-04 09:15:58
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 收入列表
 * @Motto: Write the code. Change the world.
-->
<template>
  <section class="turnover-list">
    <!-- 筛选栏 -->
    <section class="turnover-list-section">
      <!-- <a-space> -->
      <a-row :gutter="[16, 16]">
        <a-col :span="$store.getters.isMobile ? 24 : undefined"
        >
          <a-input-search
              v-model:value="searchValue.keywords"
              placeholder="请搜索租客、房号"
              :style="{ width: $store.getters.isMobile ? '100%' : '250px' }"
              @search="handleFilterChange()"
              allowClear
          />
        </a-col>
        <a-col :span="$store.getters.isMobile ? 12 : undefined">
          <a-select
              v-model:value="searchValue.contract_status"
              placeholder="请选择合同状态"
              :style="{ width: $store.getters.isMobile ? '100%' : '250px' }"
              @change="handleFilterChange()"
              allowClear
          >
            <a-select-option
                v-for="item of initData.contractStatus"
                :key="item.key"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 12 : undefined">
          <a-select
              v-model:value="searchValue.is_confirm"
              placeholder="请选择是否确认"
              :style="{ width: $store.getters.isMobile ? '100%' : '250px' }"
              allowClear
              @change="handleFilterChange()"
          >
            <a-select-option v-for="item of initData.isConfirm" :key="item.key">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-col>
      </a-row>
      <a-button v-permission="['incomeList', 'auth', 'incomeConfirmRuleList']" type="primary"
                @click="clickConfirmRules"
      >收入确认规则
      </a-button
      >
      <!-- </a-space> -->
    </section>
    <!-- 统计模块 -->
    <section class="staticis">
      <!-- style="height: 80px" -->
      <a-row
          type="flex"
          justify="space-around"
          align="middle"
          :style="{ height: $store.getters.isMobile ? undefined : '80px' }"
      >
        <a-col :span="$store.getters.isMobile ? 12 : 4">
          <a-statistic
              :value="staticData.receivableByTax"
              title="当月应收（含税）"
          >
          </a-statistic>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 12 : 4">
          <a-statistic
              :value="staticData.receivableNotTax"
              title="当月应收（不含税）"
          >
          </a-statistic>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 12 : 4">
          <a-statistic :value="staticData.actualByTax" title="当月实收（含税）">
          </a-statistic>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 12 : 4">
          <a-statistic
              :value="staticData.actualNotTax"
              title="当月实收（不含税）"
          >
          </a-statistic>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 12 : 4">
          <a-statistic
              :value="staticData.confirmedAmount"
              title="当月已确定收入"
          >
          </a-statistic>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 12 : 4">
          <a-statistic
              :value="staticData.confirmingAmount"
              title="当月待确定收入"
          >
          </a-statistic>
        </a-col>
      </a-row>
    </section>
    <!-- 表格 -->
    <a-table
        sticky
        ref="tableRef"
        :dataSource="dataList"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
        :scroll="{ x: 'max-content' }"
        class="mt-10"
        :row-selection="rowSelection"
        :customRow="customRow"
        :key="tableKey"
    >
      <template #title>
        <div class="tips-box" v-if="selectedRowKeys.length">
          <a-alert type="warning">
            <template #description>
              <p>
                确认收入蓝色代表待确认收入，黑色代表已确认收入，已确认的收入可以取消确认。
              </p>
              <p>
                取消确认：对最后一个已确认金额进行取消确认。一键取消确认：对勾选列表的全部已确认金额进行取消确认。
              </p>
              <p>合同退租审核通过之后，最后一个待确认金额改变，已确认收入不改变。</p>
            </template>
          </a-alert>
        </div>
        <a-row
            class="table-header"
            :style="{
            padding: $store.getters.isMobile ? '5px' : '',
          }"
        >
          <a-col style="flex-shrink: 0;margin-right: 4px"> 收入列表</a-col>
          <template v-if="!selectedRowKeys.length">
            <a-col>
              <a-space>
                <a-button
                    type="primary"
                    v-permission="['incomeList', 'auth', 'syncBill']"
                    ghost
                    :loading="syncLoading"
                    @click="handleSyncBillData"
                >同步账单数据
                </a-button
                >
                <a-month-picker
                    v-model:value="selectedMonth"
                    placeholder="请选择月份"
                    @change="handleFilterChange(true)"
                    :format="monthFormat"
                    :valueFormat="monthFormat"
                    :allowClear="false"
                    :style="{ width: $store.getters.isMobile ? '100px' : '' }"
                />
                <a-select
                    v-model:value="feeType"
                    placeholder="请选择"
                    :style="{ width: $store.getters.isMobile ? '172px' : '180px' }"
                    @select="handleFilterChange(false, 'type')"
                    :options="initData.newComputeType"
                    :fieldNames="{
                    label: 'name',
                    value: 'key',
                    }"
                >
                </a-select>
                <a-button type="primary" ghost :loading="exportLoading" @click="handleExport"
                >收入统计报表导出
                </a-button
                >
              </a-space>
            </a-col>
          </template>
          <template v-else>
            <!--   选中了某些列   -->
            <a-col :flex="1">
              <a-row :gutter="[6, 6]" :wrap="true" justify="end">
                <a-col>
                  <a-button
                      type="primary"
                      ghost
                      :disabled="selectedRowKeys.length > 1"
                      :loading="editLoading"
                      @click="handleEditRow"
                  >{{ isEdit ? '保存' : '编辑' }}
                  </a-button
                  >
                </a-col>
                <a-col>
                  <a-button type="primary" :disabled="isEdit" ghost @click="handleIncomeVerifyOnce"
                  >确认收入
                  </a-button
                  >
                </a-col>
                <a-col>
                  <a-button
                      danger
                      ghost
                      @click="handleCancelVerify('one')"
                      :disabled="selectedRowKeys.length > 1 || isEdit"
                  >取消确认
                  </a-button
                  >
                </a-col>
                <a-col>
                  <a-button
                      danger
                      ghost
                      :disabled="selectedRowKeys.length > 1 || isEdit"
                      @click="handleCancelVerify"
                  >一键取消确认
                  </a-button
                  >
                </a-col>
                <!--                <a-col>-->
                <!--                  <a-button-->
                <!--                    type="primary"-->
                <!--                    ghost-->
                <!--                    :disabled="selectedRowKeys.length > 1 || isEdit"-->
                <!--                    @click="handleAmortizeCustom('lease')"-->
                <!--                  >免租期摊销</a-button-->
                <!--                  >-->
                <!--                </a-col>-->
                <!--                <a-col>-->
                <!--                  <a-button-->
                <!--                    type="primary"-->
                <!--                    ghost-->
                <!--                    :disabled="selectedRowKeys.length > 1 || isEdit"-->
                <!--                    @click="handleAmortizeCustom('amount')"-->
                <!--                  >减免金额摊销</a-button-->
                <!--                  >-->
                <!--                </a-col>-->
                <a-col>
                  <a-button type="primary" ghost :disabled="isEdit || selectedRowKeys.length > 10"
                            @click="handleRegenerate"
                  >重新生成
                  </a-button
                  >
                </a-col>
                <a-col>
                  <a-button
                      type="primary"
                      ghost
                      :disabled="selectedRowKeys.length > 1 || isEdit"
                      @click="handleEditPlan"
                  >修改计划收入
                  </a-button
                  >
                </a-col>
                <a-col>
                  <a-button type="primary" ghost :disabled="isEdit" @click="handleIncomeVerify"
                  >一键确认收入
                  </a-button
                  >
                </a-col>
                <a-col>
                  <a-button type="primary" ghost :disabled="isEdit" @click="handleExport"
                  >收入统计报表导出
                  </a-button
                  >
                </a-col>
              </a-row>
            </a-col>
          </template>

        </a-row>
      </template>
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'owner_name'">
          <a @click.stop="toOwnerDetail(record)">
            {{ text }}
          </a>
        </template>
        <template v-if="column.key === 'cost_type'">
          <span> {{ record.cost_type_txt || "--" }}</span>
        </template>
        <template v-if="column.key === 'contract_number'">
          <span>{{ record?.contract_id ? text || '--' : '--' }}</span>
        </template>
        <template v-if="column.renderKey === 'monthRender'">
          <template v-if="text">
            <template v-for="item of incomeTypeFilterOptions" :key="item.key">
              <div v-if="item.key !== 'confirm_income_amount'">{{ text[item.key] }}</div>
              <template v-else>
                <template v-if="text.is_confirm == 0">
                  <!--   未确认展示--    -->
                  <div>--</div>
                </template>
                <template v-else>
                  <a-input-number
                      v-if="isEdit && selectedRowKeys[0] == record.id && text.is_confirm == 1"
                      class="w-100p"
                      :class="text.is_confirm == 1 ? 'to-be-confirm-value' : ''"
                      placeholder="请输入"
                      v-model:value="text[item.key]"
                      @change="handleToBeConfirmChange(text)"
                      :min="0"
                      :precision="2"
                      @click.stop
                  />
                  <div :class="text.is_confirm == 1 ? 'to-be-confirm-value' : ''" v-else>
                    {{ text[item.key] }}
                  </div>
                </template>
              </template>
            </template>
          </template>
          <span v-else>--</span>
        </template>
        <template v-if="column.key === 'income_type'">
          <template v-for="item of incomeTypeFilterOptions" :key="item.key">
            <div
            >
              {{ item.name }}
            </div>
          </template>
        </template>
      </template>
    </a-table>

    <!-- 账单详情 -->
    <BillDetailDrawer
        :visible="billDetailVisible"
        :id="billDetailId"
        @cancel="billDetailVisible = false"
    />

    <!-- 租客详情 -->
    <OwnerDetailDrawer
        :visible="ownerDetailVisible"
        :id="ownerId"
        @cancel="ownerDetailVisible = false"
    />

    <!--  收入规则  -->
    <IncomeConfirmRule
        :visible="rulesVisible"
        @handleCancel="rulesVisible = false"
    />

    <!--  一键确认收入   -->
    <IncomeVerifyModal
        :visible="verifyVisible"
        :selectedRowKeys="selectedRowKeys"
        @handleCancel="verifyVisible = false"
        @handleSuccess="handleIncomeVerifySuccess"
    />

    <!--  修改计划收入  -->
    <EditPlanAmountModal
        :visible="editPlanVisible"
        :selectedRowKeys="selectedRowKeys"
        @handleCancel="editPlanVisible = false"
        @handleSuccess="handleEditPlanSuccess"
    />

    <!--  xx摊销自定义   -->
    <AmortizeCustomModal
        :visible="amortizeCustomVisible"
        @handleCancel="amortizeCustomVisible = false"
    />
  </section>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  watch,
  reactive,
  toRaw,
  onActivated,
  createVNode,
  toRefs,
  nextTick,
} from "vue";
// import { PlusOutlined } from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import store from "../../../store";
import {message, Modal, notification} from "ant-design-vue";
import {useRouter} from "vue-router";
import moment from "moment";
import {
  DownloadOutlined,
  ExclamationCircleOutlined,
  CalendarOutlined,
} from "@ant-design/icons-vue";
import BLCOMMON from "bl-common-vue3";
import _ from "lodash";
import BillDetailDrawer from "@/views/bill/BillDetail/modules/BillDetailDrawer.vue";
import OwnerDetailDrawer from "@/views/village/OwnerManage/modules/OwnerDetailDrawer.vue";
import IncomeConfirmRule from "@/views/bill/IncomeList/modules/IncomeConfirmRule.vue";
import IncomeVerifyModal from "@/views/bill/IncomeList/modules/IncomeVerifyModal.vue";
import EditPlanAmountModal from "@/views/bill/IncomeList/modules/EditPlanAmountModal.vue";
import AmortizeCustomModal from "@/views/bill/IncomeList/modules/AmortizeCustomModal.vue";

const monthFormat = "YYYY-MM";

export default defineComponent({
  name: "incomeList",
  components: {
    OwnerDetailDrawer,
    BillDetailDrawer,
    DownloadOutlined,
    CalendarOutlined,
    IncomeConfirmRule,
    IncomeVerifyModal,
    EditPlanAmountModal,
    AmortizeCustomModal,
  },
  setup() {
    const $router = useRouter();

    const searchValue = reactive({
      keywords: "",
      contract_status: undefined,
      is_confirm: undefined,
    });
    const tableRef = ref(null);
    const columns = ref([]);
    const staticData = ref({});
    const selectedMonth = ref(moment().format(monthFormat));
    const dataList = ref([]);
    const feeType = ref(1);
    const incomeType = ref([]);
    const costType = ref([]);

    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const loading = ref(false);

    const state = reactive({
      detailVisible: false,
      selectedRowKeys: [], // 选择的列表id
      billDetailVisible: false,
      billDetailId: 0,
      ownerDetailVisible: false,
      ownerId: 0,
      rulesVisible: false,
      isEdit: false,
      verifyVisible: false,
      editPlanVisible: false,
      amortizeCustomVisible: false,
      toBeConfirmInfo: {},
      editLoading: false,
      tableKey: 0,
      hasRefresh: false,
      syncLoading: false,
      exportLoading: false,
    });

    const isAllFeeType = computed(() => {
      return feeType.value == 1;
    });

    // 按合同费用类型查看、按合同合并查看、按租客费用类型查看、按租客合并查看下收入类型不显示确认收入，并且不显示复选框
    const rowSelection = computed(() =>
        isAllFeeType.value && dataList.value?.length
            ? {
              selectedRowKeys: state.selectedRowKeys,
              onChange: onSelectedRowChange,
            }
            : null
    );

    const incomeTypeOptions = computed(() => {
      return isAllFeeType.value ? initData.value?.newIncomeType || [] : (initData.value?.newIncomeType || []).filter((v) => v.key !== "confirm_income_amount")
    });

    const incomeTypeFilterOptions = computed(() => {
      return incomeType.value?.length ? incomeTypeOptions.value.filter((v) => incomeType.value.includes(v.key)) : incomeTypeOptions.value;
    });


    const onSelectedRowChange = (keys) => {
      // if (keys.length > 100) {
      //   notification.warning({
      //     message: "警告",
      //     description: "您最多可勾选100项",
      //   });
      //   return;
      // }
      state.selectedRowKeys = keys;
    };
    /**
     * @description:  table
     */

    const handleFilterChange = (init = false, type) => {
      if (init) {
        getStatisticsData();
      }
      if (type == 'type') {
        // 切换类型 清空选择项 清空 筛选值 更改收入类型可筛选项
        state.selectedRowKeys = [];
        costType.value = [];
        incomeType.value = [];
      }
      if (init || type) {
        state.hasRefresh = true;
      }
      getTableData(true);
    };

    const getDateCols = () => {
      const currentYear = moment(selectedMonth.value).get("year");
      const currentMonth = moment(selectedMonth.value).get("month") + 1;
      let monthArr = [];
      // 上一年
      for (let i = currentMonth; i <= 12; i++) {
        monthArr.push(`${currentYear - 1}-${i < 10 ? "0" + i : i}`);
      }
      // 当年
      for (let i = 1; i <= 12; i++) {
        monthArr.push(`${currentYear}-${i < 10 ? "0" + i : i}`);
      }
      // 下一年
      for (let i = 1; i <= currentMonth; i++) {
        monthArr.push(`${currentYear + 1}-${i < 10 ? "0" + i : i}`);
      }
      for (let i = 0; i < monthArr.length; i++) {
        columns.value.push({
          title: monthArr[i],
          dataIndex: monthArr[i],
          key: monthArr[i],
          width: 160,
          renderKey: "monthRender",
        });
      }


      const tableScrollToColumn = async (tableElement, columnIndex, fixedNum = 0) => {
        await nextTick();
        const theTableColumn = tableElement.querySelector('.ant-table-row')
        let scrollLeft = 0
        for (let i = fixedNum; i < theTableColumn.children.length; i++) {
          if (i == columnIndex) {
            break
          }
          scrollLeft += theTableColumn.children[i].offsetWidth
        }
        setTimeout(() => {
          // tableEl.scrollLeft = targetColumn.offsetLeft + 777;
          tableElement.scrollTo({
            behavior: 'smooth',
            left: scrollLeft,
          })
        }, 100)
      };

      if (state.hasRefresh) {
        let monthIndex = columns.value.findIndex((v) => v.key === selectedMonth.value);
        let fixedNum = columns.value.filter((v) => v.fixed)?.length;
        tableScrollToColumn(tableRef.value.tableRef.$el.querySelector('.ant-table-body'), monthIndex, fixedNum);
        state.hasRefresh = false;
      }
    };

    const setInitCols = () => {
      let _columns = [
        {
          title: BLCOMMON.utils.L("租客"),
          dataIndex: "owner_name",
          key: "owner_name",
          width: 80,
          fixed: "left",
          show: [1, 2, 3, 4, 5],
        },
        {
          title: "楼宇名称",
          dataIndex: "build_name",
          width: 100,
          fixed: store.getters.isMobile ? undefined : "left",
          show: [1, 2, 3],
          customRender: ({text, record, index}) => {
            return text ? text : Array.isArray(record?.build_bind?.build) ? record.build_bind.build.map((v) => v.build_name).join(',') : record?.build_bind?.build?.build_name || '';
          },
        },
        {
          title: "房号",
          dataIndex: "room_number_txt",
          key: "room_number_txt",
          width: 100,
          fixed: store.getters.isMobile ? undefined : "left",
          show: [1, 2, 3],
        },
        {
          title: "所属公司",
          dataIndex: "org_branch_name",
          key: 'org_branch_name',
          width: 100,
          fixed: store.getters.isMobile ? undefined : "left",
          show: [1, 2, 3],
        },
        {
          title: "合同编号",
          dataIndex: "contract_number",
          key: "contract_number",
          fixed: store.getters.isMobile ? undefined : "left",
          width: 160,
          show: [1, 2, 3],
        },
        {
          title: "客商编号",
          dataIndex: "tenant_no",
          key: "tenant_no",
          fixed: store.getters.isMobile ? undefined : "left",
          width: 100,
          show: [1, 2, 3, 4, 5],
          customRender: ({text, record, index}) => {
            return text || "--";
          },
        },
        {
          title: "费用类型",
          dataIndex: "cost_type",
          key: "cost_type",
          width: 105,
          fixed: store.getters.isMobile ? undefined : "left",
          filters: initData.value.costType.map((item) => ({
            text: item.name,
            value: item.key,
          })),
          filteredValue: costType.value || null,
          show: [1, 2, 4,],
        },
        {
          title: "收入类型",
          dataIndex: "income_type",
          key: "income_type",
          width: 120,
          fixed: store.getters.isMobile ? undefined : "left",
          filters: incomeTypeOptions.value.map((item) => ({
            text: item.name,
            value: item.key,
          })),
          filteredValue: incomeType.value || null,
          show: [1, 2, 3, 4, 5],
        },
      ];
      columns.value = _columns.filter((item) => {
        return item.show.includes(feeType.value);
      });
      getDateCols();
    };

    const handleTableChange = (pager, filters, sorter) => {
      dataList.value = [];
      incomeType.value = _.cloneDeep(filters.income_type?.length
          ? filters.income_type
          : undefined);
      costType.value = _.cloneDeep(filters.cost_type || []);
      page.value = pager.current;
      limit.value = pager.pageSize;
      getTableData();
    };
    const getTableData = (init = false) => {
      loading.value = true;
      if (state.hasRefresh) {
        state.tableKey++;
      }
      if (init) {
        page.value = 1;
      }
      const params = {
        page: page.value,
        limit: limit.value,
        computeDate: selectedMonth.value,
        type: feeType.value,
        ...searchValue,
      };
      if (typeof params.computeDate !== "string") {
        params.computeDate = params.computeDate.format(monthFormat);
      }
      params.cost_type = (costType.value || []).join(",");
      request
          .get("/org", "/incomeConfirm/getIncomeConfirmList", params)
          .then((res) => {
            if (res.list.length) {
              res.list.forEach((item) => {
                const {list} = item;
                list.forEach((data) => {
                  item[data.y_m] = data
                })
                item.id = `${item.contract_id}&${item.cost_type}&${item.owner_id}`
              });
            }
            total.value = res.total;
            dataList.value = res.list;
            setInitCols();
          })
          .finally(() => {
            loading.value = false;
          });
    };

    const getSelectParams = () => {
      let data = state.selectedRowKeys.map((v) => {
        let info = v.split("&");
        return {
          contract_id: info[0],
          cost_type: info[1],
          owner_id: info[2],
        }
      });
      return data;
    };

    // 收入确认规则
    const clickConfirmRules = () => {
      state.rulesVisible = true;
    };

    const iframe = document.createElement("iframe"); //导出
    let timer = null;
    // 导出
    const handleExport = () => {
      if (timer) {
        message.warn("操作过于频繁，请稍后尝试");
        return;
      }
      state.exportLoading = true;
      let data = getSelectParams();
      let params = {
        month: selectedMonth.value,
        type: feeType.value,
        data,
      };
      if (typeof params.month !== "string") {
        params.month = params.month.format(monthFormat);
      }
      request
          .post("/org", "/incomeConfirm/exportIncomeConfirm", params)
          .then((res) => {
            iframe.src = res.result.fileUrl;
            iframe.style.display = "none";
            document.body.appendChild(iframe);
            setTimeout(() => {
              document.body.removeChild(iframe);
            }, 1000);
            message.success("导出成功,请等待文件生成");

            timer = setTimeout(() => {
              timer = null;
            }, 20000);
          }).finally(() => {
        state.exportLoading = false;
      });
    };

    // 租客详情
    const toOwnerDetail = (record) => {
      state.ownerId = record.owner_id;
      state.ownerDetailVisible = true;
    };

    const closeDetail = () => {
      state.detailVisible = false;
    };
    const getStatisticsData = () => {
      let params = {
        month: selectedMonth.value,
      };
      if (typeof params.month !== "string") {
        params.month = params.month.format(monthFormat);
      }
      request.get("/org", "/incomeConfirm/incomeCensus", params).then((res) => {
        staticData.value = res.returnData;
      });
    };

    const initData = ref({});
    const getInitData = (init) => {
      request.get("/org", "/bill/incomeListInit").then((res) => {
        initData.value = res.data;
        getTableData(init);
      });
    };

    const refreshData = () => {
      state.isEdit = false;
      init();
    };

    // 同步账单数据
    const handleSyncBillData = () => {
      Modal.confirm({
        title: "提示",
        content: "即将同步账单数据到收入列表，确定要同步吗？",
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: () => {
          state.syncLoading = true;
          request
              .get("/org", "/incomeConfirm/syncIncomeConfirm", {needMsg: true})
              .then((res) => {
                message.success(res.msg || "操作成功");
                refreshData();
              }).finally(() => {
            state.syncLoading = false;
          });
        },
      });
    };

    const enterDetail = (record) => {
      if (state.isEdit) return;
      const query = {};
      if ([4, 5].includes(feeType.value)) {
        // 租客
        query.owner_id = record.owner_id;
      } else {
        if (record.owner_id) {
          query.owner_id = record.owner_id;
        }
        query.contract_id = record.contract_id;
      }
      $router.push({
        name: "incomeDetail",
        query,
      });
    };

    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => enterDetail(record),
      };
    };

    const handleEditRow = () => {
      if (state.isEdit && !_.isEmpty(state.toBeConfirmInfo)) {
        // 保存
        state.editLoading = true
        request
            .post("/org", "/incomeConfirm/editIncomeConfirm", {
              id: state.toBeConfirmInfo?.id,
              amount: state.toBeConfirmInfo?.confirm_income_amount,
              needMsg: true,
            })
            .then((res) => {
              state.editLoading = false;
              message.success(res.msg || "操作成功");
              refreshData();
            });
      } else {
        state.isEdit = !state.isEdit;
      }
    };

    const handleIncomeVerify = () => {
      // 一键确认收入
      state.verifyVisible = true;
    };

    const handleEditPlan = () => {
      state.editPlanVisible = true;
    };

    const handleAmortizeCustom = (type) => {
      state.amortizeCustomVisible = true;
    };

    const handleIncomeVerifyOnce = () => {
      // 确认收入 （可多选）
      Modal.confirm({
        title: "提示",
        content: "会确认最前一个未确认月份的确认收入，同时生成下个月的待确认收入，确定要继续吗？",
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: () => {
          let data = getSelectParams();
          request
              .post("/org", "/incomeConfirm/incomeConfirm", {
                data,
                needMsg: true,
              })
              .then((res) => {
                message.success(res.msg || "操作成功");
                refreshData();
              });
        },
      });
    };

    const handleCancelVerify = (type) => {
      // 取消确认
      Modal.confirm({
        title: "提示",
        content: type == 'one' ? "会对选择的数据的最后一个已确认金额进行取消确认（并将前一个月的确认修改成待确认），确定要继续吗？" : "会对勾选列表的全部已确认金额进行取消确认，确定要继续吗？",
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: () => {
          let url = type == 'one' ? "/incomeConfirm/cancelIncomeConfirm" : "/incomeConfirm/cancelAllIncomeConfirm";
          let data = getSelectParams();
          request
              .post("/org", url, {
                data,
                needMsg: true,
              })
              .then((res) => {
                message.success(res.msg || "操作成功");
                refreshData();
              });
        },
      });
    };


    const handleRegenerate = () => {
      // 重新生成
      Modal.confirm({
        title: "提示",
        content: "点击重新生成，计划收入将根据默认设置重新计算",
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: () => {
          let data = getSelectParams();
          request
              .post("/org", "/incomeConfirm/againCreateIncomeConfirm", {
                data,
                needMsg: true,
              })
              .then((res) => {
                message.success(res.msg || "操作成功");
                refreshData();
              });
        },
      });
    };

    const handleToBeConfirmChange = (info) => {
      state.toBeConfirmInfo = info;
    };

    const handleIncomeVerifySuccess = () => {
      state.verifyVisible = false;
      refreshData();
    };

    const handleEditPlanSuccess = () => {
      state.editPlanVisible = false;
      refreshData();
    };

    // 在编辑状态下 多选了 或者 不选了 取消编辑状态
    watch(
        () => state.selectedRowKeys,
        (val) => {
          if (val.length > 1 || !val?.length) {
            if (state.isEdit) {
              state.isEdit = false;
              getTableData();
            }
          }
        }
    );

    watch(
        () => state.isEdit,
        (val) => {
          if (!val) {
            // 非编辑状态
            state.editLoading = false;
            state.toBeConfirmInfo = {};
          }
        }
    );


    const init = (init = false) => {
      getInitData(init);
      getStatisticsData();
    };

    onActivated(() => {
      state.hasRefresh = true;
      init();
    });

    return {
      columns,
      dataList,
      pagination,
      loading,
      staticData,
      searchValue,
      initData,
      selectedMonth,
      feeType,
      monthFormat,
      incomeType,
      costType,
      rowSelection,
      isAllFeeType,
      incomeTypeOptions,
      incomeTypeFilterOptions,
      ...toRefs(state),
      tableRef,
      handleFilterChange,
      handleTableChange,
      clickConfirmRules,
      closeDetail,
      toOwnerDetail,
      handleSyncBillData,
      handleExport,
      handleEditRow,
      handleIncomeVerify,
      handleEditPlan,
      handleAmortizeCustom,
      customRow,
      handleIncomeVerifyOnce,
      handleCancelVerify,
      handleRegenerate,
      handleToBeConfirmChange,
      handleIncomeVerifySuccess,
      handleEditPlanSuccess,
    };
  },
});
</script>

<style lang="less" scoped>
.turnover-list {
  padding: 10px;

  .table-header {
    padding: 0 10px;
    color: rgba(0, 0, 0, 0.8);
    line-height: 32px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: nowrap;
  }

  .staticis {
    background: #fff;
    margin-top: 10px;
    width: 100%;
    padding: 10px;
  }

  .turnover-list-section {
    display: flex;
    justify-content: space-between;
  }

  .action-center {
    display: inline-block;
    width: 50%;
    text-align: center;
  }

  .turnover-badge {
    color: inherit;
  }
}

.income-tab {
  background-color: #fff;

  :deep(.ant-tabs-bar) {
    padding-right: 10px;
    border-bottom: none;
  }
}

.tips-box {
  padding: 0 10px 10px 10px;
}

:deep(.ant-alert-description) {
  font-size: 12px;

  p {
    margin-bottom: 6px;

    &:last-of-type {
      margin-bottom: 0;
    }
  }
}

:deep(.ant-alert-with-description.ant-alert-no-icon) {
  padding: 6px 10px;
}

.to-be-confirm-value {
  color: @primary-color !important;
}
</style>
